/**
 * Copyright (c) 2018, Mr.Wang (recallcode@aliyun.com) All rights reserved.
 */

package com.bdi.mqtt_broker.mqtt_protocol;


import com.bdi.mqtt_broker.config.BrokerConfig;
import com.bdi.mqtt_broker.constant.Constants;
import com.bdi.mqtt_broker.model.SessionStore;
import com.bdi.mqtt_broker.service.ChannelManagerService;
import com.bdi.mqtt_broker.service.ISessionStoreService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.mqtt.*;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * PINGREQ连接处理
 */
@Slf4j
public class PingReq {

    private final ISessionStoreService sessionStoreService;
    private final BrokerConfig brokerConfig;
    private final ChannelManagerService channelManagerService;

    public PingReq(ISessionStoreService sessionStoreService, BrokerConfig brokerConfig, ChannelManagerService channelManagerService) {
        this.sessionStoreService = sessionStoreService;
        this.brokerConfig = brokerConfig;
        this.channelManagerService = channelManagerService;
    }

    public void processPingReq(Channel channel, MqttMessage msg) {
        String clientId = (String) channel.attr(AttributeKey.valueOf(Constants.CHANNEL_ATTRIBUTE_CLIENT_ID)).get();
        if (sessionStoreService.containsKey(clientId)) {
            SessionStore sessionStore = sessionStoreService.get(clientId);
            ChannelId channelId = channelManagerService.get(sessionStore.getBrokerId() + "_" + sessionStore.getChannelId());
            if (brokerConfig.getBrokerId().equals(sessionStore.getBrokerId()) && channelId != null) {
                MqttMessage pingRespMessage = MqttMessageFactory.newMessage(
                        new MqttFixedHeader(MqttMessageType.PINGRESP, false, MqttQoS.AT_MOST_ONCE, false, 0), null, null);
                log.debug("PINGREQ - clientId: {}", clientId);
                channel.writeAndFlush(pingRespMessage);
            }
        }
    }

}
